import 'package:dio/dio.dart';

import '../math.dart';
import '../typings.dart';

const int HTTP_STATUS_OK = 200;
const int DEFAULT_BENCHMARK_DIO_CONNECT_TIMEOUT = 5000;
const int DEFAULT_BENCHMARK_DIO_RECEIVE_TIMEOUT = 5000;

Future<MeasurementResult> measure(MeasurementRequest measureRequest) async {
  final di = _createDio();
  var isRoundOne = true;
  var startupWithConnectivityIssue = false;
  final summary = await avg(() async {
    if (startupWithConnectivityIssue) throw DioError();
    final isRoundOneSnapshot = isRoundOne;
    isRoundOne = false;
    Response resp;
    try {
      resp = await di.get(measureRequest.uri);
    } on DioError catch(ex) {
      if (isRoundOneSnapshot) startupWithConnectivityIssue = true;
      throw ex;
    }
    if (resp.statusCode != HTTP_STATUS_OK) {
      throw Exception('network measure failure...${measureRequest.uri}');
    }
  })(measureRequest.sampleTimes);
  return MeasurementResult(measureRequest, summary: summary);
}

Dio _createDio() {
  BaseOptions options = new BaseOptions();
  options.connectTimeout = DEFAULT_BENCHMARK_DIO_CONNECT_TIMEOUT;
  options.receiveTimeout = DEFAULT_BENCHMARK_DIO_RECEIVE_TIMEOUT;
  return new Dio(options);
}
